package database

import (
	parseConfig "poc-yiliao-go/common/parseConfig"

	mgo "gopkg.in/mgo.v2"
)

// Mongo mongoDB对象，注意需要defer Mongo.Session.Close()
type Mongo struct {
	url            string
	dBName         string
	collectionName string
	Session        *mgo.Session
	Collection     *mgo.Collection
}

// SetupMongo 建立mongo Collection
func SetupMongo() (Mongo, error) {
	var mongo Mongo
	config, err := parseConfig.New()
	if err != nil {
		return mongo, err
	}
	mongo.url = config.Get("mongoURL").(string)
	mongo.dBName = config.Get("mongoDB").(string)
	mongo.collectionName = config.Get("mongoCollection").(string)

	mongo.Session, err = mgo.Dial(mongo.url) //连接数据库
	if err != nil {
		return mongo, err
	}

	mongo.Session.SetMode(mgo.Monotonic, true)

	db := mongo.Session.DB(mongo.dBName)          //数据库名称
	mongo.Collection = db.C(mongo.collectionName) //如果该集合已经存在的话，则直接返回

	return mongo, nil
}
